function ListNode(val, next) {
    this.val = (val === undefined ? 0: val)
    this.next = (next === undefined ? null : next)
}
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
// 输出的格式不对
var addTwoNumbers = function(l1, l2) {

    // 存放最终的结果
    let result = []
    let first = []
    let second = []
    let pre
    let cur
    let add
    while (l1 != null || l2 != null) {

        first.push((l1 != null) ? l1.val: 0 )
        second.push((l2 != null) ? l2.val : 0)
        if (l1 != null) l1 = l1.next
        if (l2 != null) l2 = l2.next
    }
    pre = first.reverse().join('')
    cur = second.reverse().join('')
    res = (Number(pre) + Number(cur)).toString().split('').reverse()
    for (let i = 0 ; i< res.length; i++) {
        result.push(res[i])
    }
    return result
    // console.log(typeof((Number(pre) + Number(cur))))


};

var addTwoNumbers = function(l1, l2) {
    /*
    输出的方式要以链表为格式 所以在进行存储的时候 要创建链表的形式并且判断进位
    * */
    // 创建一个哑节点
    let newHead = new ListNode('0')
    // 保存链表的头位置用于最后的返回
    let head = newHead
    // 存在进位
    let addOne = 0
    while (addOne || l1 || l2) {
        // 存在两个链表的长度不相等的情况
        let val1 = l1 != null ? l1.val : 0
        let val2 = l2 != null ? l2.val : 0
        let r1 = val1 + val2 + addOne
        addOne = r1 >= 10 ? 1: 0
        newHead.next = new ListNode(r1 % 10) // newHead 的下一个节点 因为结果是大于10 的所以要进行取余
        newHead = newHead.next
        if (l1) l1 = l1.next
        if (l2) l2 = l2.next
    }
    return head.next
}

let l1 = new ListNode(2)
let p1 = new ListNode(4)
let p2 = new ListNode(3)
l1.next = p1
p1.next = p2

let l2 = new ListNode(5)
let p3 = new ListNode(6)
let p4 = new ListNode(4)
l2.next = p3
p3.next = p4

console.log(addTwoNumbers(l1,l2))
